package com.es.service;

import com.alibaba.fastjson.JSON;
import com.es.entity.Content;
import com.es.utils.HtmlParseUtil;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ParseServiceImpl implements ParseService {

    private final HtmlParseUtil htmlParseUtil;
    private final RestHighLevelClient restHighLevelClient;

    @Autowired
    public ParseServiceImpl(HtmlParseUtil htmlParseUtil, RestHighLevelClient restHighLevelClient) {
        this.htmlParseUtil = htmlParseUtil;
        this.restHighLevelClient = restHighLevelClient;
    }


    @Override
    public Boolean parseSource(String keywords) throws Exception {
        if (keywords == null || keywords.length() == 0) {
            return false;
        }
        List<Content> contents = htmlParseUtil.parseJD(keywords);
        BulkRequest request = new BulkRequest();
        for (int i = 0; i < contents.size(); i++) {
            request.add(new IndexRequest("jd").source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
        }
        return !restHighLevelClient.bulk(request, RequestOptions.DEFAULT).hasFailures();
    }

    @Override
    public List<Map<String, Object>> searchPage(String keyword, Integer pageNum, Integer pageSize) throws IOException {
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 10;
        }
        // 条件搜索
        SearchRequest request = new SearchRequest("jd");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 精准匹配
        TermQueryBuilder name = QueryBuilders.termQuery("name", keyword);
        // 封装条件
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchSourceBuilder.query(name);
        // 分页
        searchSourceBuilder.from(pageNum).size(pageSize);
        request.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        List<Map<String, Object>> map = new LinkedList<>();
        for (SearchHit searchHit : search.getHits().getHits()) {
            map.add(searchHit.getSourceAsMap());
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> highlightPage(String keyword, Integer pageNum, Integer pageSize) throws IOException {
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 10;
        }
        // 条件搜索
        SearchRequest request = new SearchRequest("jd");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 精准匹配
        TermQueryBuilder name = QueryBuilders.termQuery("name", keyword);
        // 封装条件
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchSourceBuilder.query(name);
        // 分页
        searchSourceBuilder.from(pageNum).size(pageSize);
        request.source(searchSourceBuilder);
        // 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        highlightBuilder.requireFieldMatch(false);
        searchSourceBuilder.highlighter(highlightBuilder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        List<Map<String, Object>> map = new LinkedList<>();
        for (SearchHit searchHit : search.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            HighlightField nameHigh = highlightFields.get("name");
            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
            if (nameHigh != null) {
                Text[] fragments = nameHigh.getFragments();
                String field = "";
                for (Text fragment : fragments) {
                    field += fragment;
                }
                sourceAsMap.put("name", field);
            }
            map.add(sourceAsMap);
        }
        return map;
    }
}
